<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" size="default" @click="showAddRoleDialog"
          >添加角色</el-button
        >
      </div>
      <el-table :data="rolesList" stripe border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 数据需要用3个for嵌套渲染，采用栅格式分开 -->
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['bdBottom', index === 0 ? 'bdTop' : '', 'vcenter']"
            >
              <!-- 1级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdTop', 'vcenter']"
                  v-for="(item_child1, index2) in item.children"
                  :key="item_child1.id"
                >
                  <!-- 2级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item_child1.id)"
                      >{{ item_child1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 3级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="item_child2 in item_child1.children"
                      :key="item_child2.id"
                      closable
                      @close="removeRightById(scope.row, item_child2.id)"
                      >{{ item_child2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>{{ scope.row }}</pre>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="id" label="ID" width="180"> </el-table-column>

        <el-table-column prop="roleName" label="角色名" width="180">
        </el-table-column>

        <el-table-column prop="roleDesc" label="角色描述" width="120">
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑角色按钮 -->
            <el-button type="primary" icon="el-icon-edit">编辑</el-button>
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >

            <!-- 角色删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的Dialog -->
    <el-dialog
      title="提示"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <span>分配权限菜单栏</span>
      <el-tree
        :data="rightList"
        show-checkbox
        node-key="id"
        :default-checked-keys="defkeys"
        :props="treeProps"
        default-expand-all
        ref="treeRef"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close="addRoleDialogClose"
    >
      <span>这是一段信息</span>
      <el-form
        :model="addRoleParams"
        ref="addRoleFormRef"
        :rules="addRoleRules"
        label-width="80px"
        :inline="false"
        size="normal"
  
      >
        <!-- id -->
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="addRoleParams.roleId"></el-input>
        </el-form-item>

        <!-- 名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleParams.roleName"></el-input>
        </el-form-item>

        <!-- Desc -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleParams.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
export default {
  data() {
    return {
      rolesList: [], //角色列表数据
      rightList: [], //权限数据
      setRightDialogVisible: false, //是否开关更改权限的Dialog弹窗界面
      treeProps: {
        //treeProps这里用于传送Dialog el-tree标签的props
        label: "authName",
        children: "children",
      },
      defkeys: [], //当前角色权限 在DIalog里 checkbox选中的id数组
      roleId: "", //存放scope.row获取的该行角色数据id值，用于发post请求分配权限
      addRoleParams: { roleId: 0, roleName: "", roleDesc: "" },

      addRoleDialogVisible: false, //添加角色

      addRoleRules: {
        roleId: [
          { required: true, message: "请输入id ", trigger: "blur" },
        ],
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getRolesList("list");
  },

  methods: {
    // 获取所有角色列表
    async getRolesList(type) {
      const { data: res } = await this.$http.get(`roles`);
      this.rolesList = res.data;
      console.log(this.rolesList);
    },

    // 根据ID删除对应权限
    async removeRightById(role, rightId) {
      // 弹框确定是否删除MessageBox
      const confirmResult = await this.$confirm(
        "此操作将删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message({ type: "info", message: "取消删除!" });
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败，可能是服务器问题");
      }

      // this.getRolesList();

      // 如何解决删除权限后被刷新，我的想法是roleID直接接受scope.row.id，然后发现最好别这样，因为删除权限后要使用role.children=res.data来重新渲染
      role.children = res.data;
      return this.$message.success("删除成功");
    },

    // 通过递归获取角色 三级权限下 所有的ID，并保存在数组defKey中
    getLeafKeys(node, arr) {
      // 当前节点没有children说明是三阶节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr)); //箭头函数的写法，别忘记
    },

    // 删除角色

    async deleteRole(role) {
      const confirmResult = await this.$confirm(
        "此操作将删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message({ type: "info", message: "取消删除!" });
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
           this.getRolesList();
      return this.$message.success("删除成功");

    },

    showAddRoleDialog() {
      this.addRoleDialogVisible = true;
    },

    // 添加角色
    async addRole() {
      const { data: res } = await this.$http.post(`roles`,this.addRoleParams);
      console.log(res);
      if (res.meta.status !== 201) {
        return this.$message.error("post添加角色失败，可能是服务器问题");
      }
      this.addRoleDialogVisible = false;
      this.getRolesList();
      return this.$message.success("post添加用户成功");
    },

    //
    addRoleDialogClose(){
      this.$refs.addRoleFormRef.resetFields();
    },

    // 显示分配角色权限Dialog并且调用 获取角色三级权限的id值，将id值传给 :default-checked-keys="defkeys"
    async showSetRightDialog(role) {
      this.roleId = role.id; //存放当前行选中的分配权限 role的值是scope.row获取得来的
      const { data: res } = await this.$http.get(`rights/tree`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据全列表失败");
      }
      this.rightList = res.data;
      console.log(this.rightList); //获取rightList数组内容

      this.getLeafKeys(role, this.defkeys); //获取Dialog所有结点的ID
      this.setRightDialogVisible = true;
    },
    // 监听角色分配Dialog关闭，清空defkeys，保证第二次打开分配权限的时候，不会因为里面有id数据而混乱
    setRightDialogClosed() {
      this.defkeys = [];
    },

    // 分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);
      // 以","拼接字符串
      const idStr = keys.join(",");
      console.log(idStr);
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.defkeys = res;
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdBottom {
  border-bottom: 1px solid rgb(184, 184, 184);
}
.bdTop {
  border-top: 1px solid rgb(184, 184, 184);
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>